import React, { useState, useRef } from 'react';
import { Form, Input, Button, Typography, Spin, message, Card, Row, Col, Select, DatePicker } from 'antd';
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { RangePicker } = DatePicker;
import type { Dayjs } from 'dayjs';

export default function TravelStrategy() {
  const [form] = Form.useForm();
  const [isGenerating, setIsGenerating] = useState<boolean>(false);
  const [generatedContent, setGeneratedContent] = useState<string>('');
  const [tourVisible, setTourVisible] = useState(false);

  // 使用HTML元素的ref引用方式
  const destinationRef = useRef<HTMLDivElement>(null);
  const travelTypeRef = useRef<HTMLDivElement>(null);
  const daysRef = useRef<HTMLDivElement>(null);
  const seasonRef = useRef<HTMLDivElement>(null);
  const attractionsRef = useRef<HTMLDivElement>(null);
  const foodRecommendationsRef = useRef<HTMLDivElement>(null);
  const submitRef = useRef<HTMLDivElement>(null);
  const resultRef = useRef<HTMLDivElement>(null);

  const showTour = () => {
    // 延迟显示，确保DOM已经渲染
    setTimeout(() => {
      setTourVisible(true);
    }, 100);
  };

  // 生成旅游攻略的模拟函数
  const generateContent = (
    destination: string,
    travelType: string,
    days: number,
    season: string,
    attractions: string,
    foodRecommendations: string
  ): string => {
    // 这里是模拟生成内容的逻辑，实际应用中应该调用AI模型
    let result = '';

    // 攻略标题
    result += `🏖️ ${destination}${days}日游全攻略 | ${travelType}必看指南\n\n`;

    // 开篇介绍
    result += `【目的地介绍】\n`;
    result += `🌍 ${destination}是一个充满魅力的地方，这里有...\n\n`;

    // 最佳旅行时间
    result += `【最佳旅行时间】\n`;
    if (season === '春季') {
      result += `🌸 ${destination}的春季气候宜人，万物复苏，是赏花的好时节。\n`;
    } else if (season === '夏季') {
      result += `☀️ ${destination}的夏季炎热湿润，是享受海滩和水上活动的最佳季节。\n`;
    } else if (season === '秋季') {
      result += `🍂 ${destination}的秋季天高云淡，气温适中，是赏秋的绝佳时机。\n`;
    } else if (season === '冬季') {
      result += `❄️ ${destination}的冬季寒冷干燥，但有独特的雪景和冬季活动。\n`;
    }

    // 行程安排
    result += `\n【行程安排】\n`;

    for (let i = 1; i <= days; i++) {
      result += `📅 **第${i}天**\n`;

      if (i === 1) {
        result += `✈️ 抵达${destination}，办理入住，稍作休息\n`;
        result += `🌃 晚上可以在附近逛逛，品尝当地特色美食\n`;
      } else if (i === days) {
        result += `🧳 整理行李，购买伴手礼\n`;
        result += `👋 结束愉快的旅程，返程回家\n`;
      } else {
        // 根据景点生成行程
        if (attractions) {
          const attrList = attractions.split('\n').filter(a => a.trim());
          const randomAttr = attrList[Math.floor(Math.random() * attrList.length)];
          result += `🏯 上午：参观${randomAttr}\n`;
        } else {
          result += `🏯 上午：参观当地著名景点\n`;
        }
        result += `🍴 中午：品尝当地特色美食\n`;
        if (travelType === '文化体验') {
          result += `🎭 下午：参加当地文化体验活动\n`;
        } else if (travelType === '自然风光') {
          result += `🏞️ 下午：欣赏自然风光\n`;
        } else if (travelType === '美食探索') {
          result += `🍰 下午：继续美食探索之旅\n`;
        } else {
          result += `🛍️ 下午：自由活动/购物\n`;
        }
        result += `🌆 晚上：欣赏夜景或参加夜间活动\n`;
      }
      result += '\n';
    }

    // 景点推荐
    result += `【景点推荐】\n`;
    if (attractions) {
      const attrList = attractions.split('\n').filter(a => a.trim());
      attrList.forEach((attr, index) => {
        result += `⭐ ${index + 1}. ${attr}\n`;
      });
    } else {
      // 生成默认景点推荐
      result += `⭐ 1. ${destination}必去的标志性景点\n`;
      result += `⭐ 2. 小众但值得一去的隐秘景点\n`;
      result += `⭐ 3. 适合拍照打卡的网红景点\n`;
    }

    // 美食推荐
    result += `\n【美食推荐】\n`;
    if (foodRecommendations) {
      const foodList = foodRecommendations.split('\n').filter(f => f.trim());
      foodList.forEach((food, index) => {
        result += `🍜 ${index + 1}. ${food}\n`;
      });
    } else {
      // 生成默认美食推荐
      result += `🍜 1. ${destination}必吃的特色小吃\n`;
      result += `🍲 2. 当地人最爱的餐厅推荐\n`;
      result += `🍹 3. 好喝的饮品和甜点\n`;
    }

    // 交通建议
    result += `\n【交通建议】\n`;
    result += `🚗 在${destination}出行，建议选择...\n`;
    result += `🚌 公共交通路线推荐...\n`;
    result += `🚕 打车注意事项...\n`;

    // 住宿建议
    result += `\n【住宿建议】\n`;
    result += `🏨 ${destination}住宿推荐...\n`;
    result += `💰 不同预算的住宿选择...\n`;

    // 实用贴士
    result += `\n【实用贴士】\n`;
    result += `📱 必备APP推荐\n`;
    result += `🧴 必带物品清单\n`;
    result += `💳 货币和支付方式\n`;
    result += `⚠️ 安全注意事项\n`;

    return result;
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      setIsGenerating(true);
      const { destination, travelType, days, season, attractions, foodRecommendations } = values;

      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 1500));

      const generated = generateContent(destination, travelType, days, season, attractions, foodRecommendations);
      setGeneratedContent(generated);
      message.success('旅游攻略生成成功！');
    } catch (error) {
      message.error('生成失败，请稍后重试');
    } finally {
      setIsGenerating(false);
    }
  };

  // 复制生成的内容
  const handleCopy = () => {
    navigator.clipboard.writeText(generatedContent).then(() => {
      message.success('内容已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  // 下载生成的内容
  const handleDownload = () => {
    const blob = new Blob([generatedContent], { type: 'text/plain;charset=utf-8' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '旅游攻略.txt';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(link.href);
    message.success('文件下载成功');
  };

  // 定义引导步骤
  const tourSteps = [
    {
      key: 'destination',
      title: '输入旅游目的地',
      description: '请输入您想要前往的旅游目的地',
    },
    {
      key: 'travelType',
      title: '选择旅行类型',
      description: '选择您的旅行风格，如文化体验、自然风光等',
    },
    {
      key: 'days',
      title: '选择旅行天数',
      description: '请选择您的旅行计划天数',
    },
    {
      key: 'season',
      title: '选择旅行季节',
      description: '选择您计划出行的季节',
    },
    {
      key: 'attractions',
      title: '景点推荐（可选）',
      description: '您可以输入推荐的景点，每行一个景点，如不填写将自动生成',
    },
    {
      key: 'foodRecommendations',
      title: '美食推荐（可选）',
      description: '您可以输入推荐的美食，每行一个美食，如不填写将自动生成',
    },
    {
      key: 'submit',
      title: '生成旅游攻略',
      description: '点击按钮生成详细的旅游攻略',
    },
    {
      key: 'result',
      title: '查看生成结果',
      description: '生成成功后，您可以在此处查看、复制或下载生成的旅游攻略',
    },
  ];

  // 组织ref引用
  const tourRefs = {
    destination: destinationRef,
    travelType: travelTypeRef,
    days: daysRef,
    season: seasonRef,
    attractions: attractionsRef,
    foodRecommendations: foodRecommendationsRef,
    submit: submitRef,
    result: resultRef,
  };

  // 旅行类型选项
  const travelTypeOptions = [
    { label: '文化体验', value: '文化体验' },
    { label: '自然风光', value: '自然风光' },
    { label: '美食探索', value: '美食探索' },
    { label: '休闲度假', value: '休闲度假' },
    { label: '购物血拼', value: '购物血拼' },
  ];

  // 季节选项
  const seasonOptions = [
    { label: '春季', value: '春季' },
    { label: '夏季', value: '夏季' },
    { label: '秋季', value: '秋季' },
    { label: '冬季', value: '冬季' },
  ];

  // 天数选项
  const daysOptions = [
    { label: '1天', value: 1 },
    { label: '2天', value: 2 },
    { label: '3天', value: 3 },
    { label: '4天', value: 4 },
    { label: '5天', value: 5 },
    { label: '6天', value: 6 },
    { label: '7天', value: 7 },
  ];

  return (
    <>
      <div style={{ padding: '24px' }}>
        <div style={{ marginBottom: 24 }}>
          <Title level={2} style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
            旅游攻略生成
            <TourGuideButton onClick={showTour} />
          </Title>
        </div>
        <Card style={{ marginBottom: '24px' }}>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            initialValues={{
              travelType: '文化体验',
              days: 3,
              season: '春季',
            }}
          >
            <Row gutter={[16, 16]}>
              <Col xs={24} md={12}>
                <Form.Item
                  name="destination"
                  label="目的地"
                  rules={[{ required: true, message: '请输入旅游目的地' }]}
                >
                  <div ref={destinationRef}>
                    <Input placeholder="请输入旅游目的地" />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="travelType"
                  label="旅行类型"
                  rules={[{ required: true, message: '请选择旅行类型' }]}
                >
                  <div ref={travelTypeRef}>
                    <Select placeholder="请选择旅行类型" options={travelTypeOptions} />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="days"
                  label="旅行天数"
                  rules={[{ required: true, message: '请选择旅行天数' }]}
                >
                  <div ref={daysRef}>
                    <Select placeholder="请选择旅行天数" options={daysOptions} />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="season"
                  label="旅行季节"
                  rules={[{ required: true, message: '请选择旅行季节' }]}
                >
                  <div ref={seasonRef}>
                    <Select placeholder="请选择旅行季节" options={seasonOptions} />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item
                  name="attractions"
                  label="景点推荐（可选）"
                >
                  <div ref={attractionsRef}>
                    <TextArea rows={3} placeholder="请输入推荐的景点，每行一个景点，如不填写将自动生成" />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item
                  name="foodRecommendations"
                  label="美食推荐（可选）"
                >
                  <div ref={foodRecommendationsRef}>
                    <TextArea rows={3} placeholder="请输入推荐的美食，每行一个美食，如不填写将自动生成" />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item>
                  <div ref={submitRef}>
                    <Button type="primary" htmlType="submit" loading={isGenerating} style={{ width: '100%' }}>
                      {isGenerating ? <Spin /> : '生成旅游攻略'}
                    </Button>
                  </div>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        {generatedContent && (
          <Card title="生成结果" extra={
            <div style={{ display: 'flex', gap: '8px' }}>
              <Button icon={<CopyOutlined />} onClick={handleCopy}>复制</Button>
              <Button icon={<DownloadOutlined />} onClick={handleDownload}>下载</Button>
            </div>
          }>
            <div ref={resultRef} style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', lineHeight: 1.6 }}>
              {generatedContent}
            </div>
          </Card>
        )}
      </div>

      <CommonTour
        open={tourVisible}
        onClose={() => setTourVisible(false)}
        steps={tourSteps}
        targetRefs={tourRefs}
      />
    </>
  );
}